﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.MenuCommand;
using RBAC_Uthorization.Read.API.DTO;
using RBAC_Uthorization.Read.API.DTO.Response.Fun;
using RBAC_Uthorization.Read.API.DTO.Response.Menu;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.MenuHandler
{
    public class MenuFindIdCommandHandlers : IRequestHandler<MenuFindIdCommand, ApiResult<MenuFindDto>>
    {
        private readonly IMenuRepository _menuRepository;
        private readonly IMapper _mapper;
        private readonly IFunctionRepository _functionRepository;
        public MenuFindIdCommandHandlers(IMenuRepository menuRepository, IMapper mapper, IFunctionRepository functionRepository)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
            _functionRepository = functionRepository;
        }
        public async Task<ApiResult<MenuFindDto>> Handle(MenuFindIdCommand request, CancellationToken cancellationToken)
        {
            //根据id查询菜单跟功能
            var menulist = await _menuRepository.GetAllAsunc(x => x.id == request.id && x.del_flag == 0 && x.sys_id == request.sys_id);
            if (menulist.Count == 0)
            {
                return new ApiResult<MenuFindDto>() { Code = ResultCode.NoContent, Message = "没有当前菜单" };
            }
            var menu = menulist.FirstOrDefault();
            var functionlist = await _functionRepository.GetAllAsunc(x => x.menu_id == menu.id && x.del_flag == 0);
            var menuFindDto = _mapper.Map<MenuFindDto>(menu);
            menuFindDto.Button = new List<FunFindDto>();
            if (functionlist.Count > 0)
            {
                foreach (var item in functionlist)
                {
                    var funFindDto = _mapper.Map<FunFindDto>(item);
                    menuFindDto.Button.Add(funFindDto);
                }
            }
          
            return new ApiResult<MenuFindDto>() { Code = ResultCode.Ok, Message = "查询成功", Data = menuFindDto };





        }
    }
}
